// 全局变量
let websocket = null;
let currentNickname = '';
let isConnected = false;
let sessionId = null;
let showingAtSuggestion = false;
let reconnectAttempts = 0;
let maxReconnectAttempts = 5;
let hasJoinedChat = false;
let isLeavingChat = false;

// 表情包相关变量
let currentPage = 1;
let totalPages = 1;
let isLoadingStickers = false;

// DOM元素
const nicknameModal = document.getElementById('nicknameModal');
const nicknameInput = document.getElementById('nicknameInput');
const joinChatBtn = document.getElementById('joinChatBtn');
const messageInput = document.getElementById('messageInput');
const sendBtn = document.getElementById('sendBtn');
const imageBtn = document.getElementById('imageBtn');
const imageInput = document.getElementById('imageInput');
const messagesList = document.getElementById('messagesList');
const onlineCountElement = document.getElementById('onlineCount');
const connectionStatusElement = document.getElementById('connectionStatus');
const charCountElement = document.getElementById('charCount');
const emojiPanel = document.getElementById('emojiPanel');
const stickerPanel = document.getElementById('stickerPanel');
const stickerGrid = document.getElementById('stickerGrid');
const stickerLoading = document.getElementById('stickerLoading');
const prevPageBtn = document.getElementById('prevPageBtn');
const nextPageBtn = document.getElementById('nextPageBtn');
const pageInfo = document.getElementById('pageInfo');
const fullscreenBtn = document.getElementById('fullscreenBtn');
const exitChatBtn = document.getElementById('exitChatBtn');
const reconnectBtn = document.getElementById('reconnectBtn');
const imageModal = document.getElementById('imageModal');
const modalImage = document.getElementById('modalImage');
const giftPanel = document.getElementById('giftPanel');
const giftGrid = document.getElementById('giftGrid');
const giftLoading = document.getElementById('giftLoading');

// 昵称验证规则
const NICKNAME_MIN_LENGTH = 1;
const NICKNAME_MAX_LENGTH = 20;
const NICKNAME_PATTERN = /^[\u4e00-\u9fa5a-zA-Z0-9_\-\s]+$/; // 支持中文、英文、数字、下划线、连字符和空格

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function () {
    initializeApp();
    
    // 确保管理员管理器在DOM加载后立即初始化
    if (typeof adminManager === 'undefined') {
        if (typeof AdminManager !== 'undefined') {
            window.adminManager = new AdminManager();
        } else {
            // 如果AdminManager还没加载，等待一下
            setTimeout(() => {
                if (typeof AdminManager !== 'undefined') {
                    window.adminManager = new AdminManager();
                }
            }, 100);
        }
    }
});

// 页面卸载时只清除localStorage，保留sessionStorage以便重连
window.addEventListener('beforeunload', function() {
    // 只清除localStorage，保留sessionStorage以便会话恢复
    localStorage.removeItem('chatNickname');
    console.log('页面卸载，保留会话状态以便重连');
});

// 页面隐藏时也清除localStorage（处理移动端场景）
document.addEventListener('visibilitychange', function() {
    if (document.hidden) {
        localStorage.removeItem('chatNickname');
    }
});

// 初始化应用
function initializeApp() {
    setupEventListeners();

    // 尝试恢复会话状态
    const savedSessionId = sessionStorage.getItem('chatSessionId');
    const savedNickname = sessionStorage.getItem('chatNickname');
    const savedJoinedStatus = sessionStorage.getItem('hasJoinedChat') === 'true';
    const sessionTimestamp = sessionStorage.getItem('sessionTimestamp');
    
    // 检查会话是否超时（24小时）
    const SESSION_TIMEOUT = 24 * 60 * 60 * 1000; // 24小时
    const isSessionExpired = sessionTimestamp && (Date.now() - parseInt(sessionTimestamp)) > SESSION_TIMEOUT;
    
    if (savedSessionId && savedNickname && !isSessionExpired) {
        console.log('尝试恢复会话状态:', { sessionId: savedSessionId, nickname: savedNickname, joined: savedJoinedStatus });
        
        // 验证会话是否有效
        validateAndRestoreSession(savedSessionId, savedNickname, savedJoinedStatus);
    } else {
        // 没有可恢复的会话或会话已超时，清除所有本地存储
        if (isSessionExpired) {
            console.log('会话已超时，清除过期会话');
            showNotification('会话已过期，请重新登录', 'info');
        }
        
        localStorage.removeItem('chatNickname');
        sessionStorage.clear();
        
        // 显示昵称设置模态框
        showNicknameModal();
        connectWebSocket();
    }
}

// 验证并恢复会话
async function validateAndRestoreSession(savedSessionId, savedNickname, savedJoinedStatus) {
    try {
        const response = await fetch(`/api/session/validate?sessionId=${encodeURIComponent(savedSessionId)}`);
        const data = await response.json();
        
        if (data.success && data.valid) {
            console.log('会话验证成功，恢复会话状态');
            
            // 恢复会话状态
            sessionId = savedSessionId;
            currentNickname = savedNickname;
            hasJoinedChat = savedJoinedStatus;
            
            // 设置全局变量
            window.sessionId = sessionId;
            window.hasJoinedChat = hasJoinedChat;
            
            // 直接连接WebSocket，不显示昵称模态框
            connectWebSocket();
            
            // 如果已经加入过聊天，启用输入框
            if (hasJoinedChat) {
                enableChatInput();
            }
            
            showNotification(`欢迎回来，${currentNickname}！`, 'success');
        } else {
            console.log('会话验证失败，清除无效会话:', data.message);
            
            // 清除无效的会话状态
            sessionStorage.clear();
            localStorage.removeItem('chatNickname');
            
            // 显示昵称设置模态框
            showNicknameModal();
            connectWebSocket();
        }
    } catch (error) {
        console.error('会话验证请求失败:', error);
        
        // 网络错误时，仍然尝试恢复会话（离线模式）
        console.log('网络错误，尝试离线恢复会话');
        
        sessionId = savedSessionId;
        currentNickname = savedNickname;
        hasJoinedChat = savedJoinedStatus;
        
        window.sessionId = sessionId;
        window.hasJoinedChat = hasJoinedChat;
        
        connectWebSocket();
        
        if (hasJoinedChat) {
            enableChatInput();
        }
        
        showNotification('网络连接异常，正在尝试恢复会话...', 'info');
    }
}

// 设置事件监听器
function setupEventListeners() {
    // 昵称输入框
    nicknameInput.addEventListener('input', function () {
        const nickname = this.value.trim();
        const isValid = validateNickname(nickname);
        joinChatBtn.disabled = !isValid;
        
        // 显示验证提示
        updateNicknameValidationTips(nickname, isValid);
    });

    nicknameInput.addEventListener('keypress', function (e) {
        if (e.key === 'Enter' && !joinChatBtn.disabled) {
            joinChat();
        }
    });

    // 加入聊天按钮
    joinChatBtn.addEventListener('click', joinChat);

    // 消息输入框
    messageInput.addEventListener('input', function () {
        const length = this.value.length;
        charCountElement.textContent = length;

        if (length > 450) {
            charCountElement.style.color = '#f44336';
        } else if (length > 400) {
            charCountElement.style.color = '#ff9800';
        } else {
            charCountElement.style.color = '#999';
        }

        // 处理@功能
        handleAtSuggestion(this.value);
    });

    messageInput.addEventListener('keypress', function (e) {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendMessage();
        }
    });

    messageInput.addEventListener('keydown', function (e) {
        // 处理Tab键选择@建议
        if (e.key === 'Tab' && showingAtSuggestion) {
            e.preventDefault();
            selectAtSuggestion();
        }
    });

    // 发送按钮
    sendBtn.addEventListener('click', sendMessage);

    // 图片按钮
    imageBtn.addEventListener('click', function () {
        imageInput.click();
    });

    // 图片输入
    imageInput.addEventListener('change', handleImageSelect);

    // 全屏按钮
    fullscreenBtn.addEventListener('click', toggleFullscreen);

    // 退出聊天按钮
    exitChatBtn.addEventListener('click', exitChat);
    reconnectBtn.addEventListener('click', manualReconnect);

    // 点击外部关闭emoji面板和表情包面板和礼物面板
    document.addEventListener('click', function (e) {
        if (!e.target.closest('.emoji-btn') && !e.target.closest('.emoji-panel')) {
            hideEmojiPanel();
        }
        if (!e.target.closest('.sticker-btn') && !e.target.closest('.sticker-panel')) {
            hideStickerPanel();
        }
        if (!e.target.closest('.gift-btn') && !e.target.closest('.gift-panel')) {
            hideGiftPanel();
        }
    });

    // 监听全屏状态变化
    document.addEventListener('fullscreenchange', updateFullscreenButton);
    document.addEventListener('webkitfullscreenchange', updateFullscreenButton);
    document.addEventListener('mozfullscreenchange', updateFullscreenButton);
    document.addEventListener('MSFullscreenChange', updateFullscreenButton);

    // 图片模态框点击关闭
    imageModal.addEventListener('click', function () {
        hideImageModal();
    });
}

// 显示昵称模态框
function showNicknameModal() {
    nicknameModal.style.display = 'flex';
    nicknameInput.focus();
}

// 隐藏昵称模态框
function hideNicknameModal() {
    nicknameModal.style.display = 'none';
}

// 验证昵称
function validateNickname(nickname) {
    if (!nickname || nickname.length < NICKNAME_MIN_LENGTH) {
        return false;
    }
    
    if (nickname.length > NICKNAME_MAX_LENGTH) {
        return false;
    }
    
    if (!NICKNAME_PATTERN.test(nickname)) {
        return false;
    }
    
    return true;
}

// 更新昵称验证提示
function updateNicknameValidationTips(nickname, isValid) {
    const tipsElement = document.querySelector('.nickname-tips p');
    
    if (!nickname) {
        tipsElement.innerHTML = '<i class="fas fa-info-circle"></i> 昵称长度为1-20个字符';
        tipsElement.style.color = '#666';
        return;
    }
    
    if (nickname.length > NICKNAME_MAX_LENGTH) {
        tipsElement.innerHTML = '<i class="fas fa-exclamation-triangle"></i> 昵称太长，最多20个字符';
        tipsElement.style.color = '#f44336';
        return;
    }
    
    if (!NICKNAME_PATTERN.test(nickname)) {
        tipsElement.innerHTML = '<i class="fas fa-exclamation-triangle"></i> 昵称只能包含中文、英文、数字、下划线、连字符和空格';
        tipsElement.style.color = '#f44336';
        return;
    }
    
    if (isValid) {
        tipsElement.innerHTML = '<i class="fas fa-check-circle"></i> 昵称格式正确';
        tipsElement.style.color = '#4caf50';
    }
}

// 加入聊天
function joinChat() {
    const nickname = nicknameInput.value.trim();
    
    // 验证昵称
    if (!validateNickname(nickname)) {
        showNotification('请输入有效的昵称', 'error');
        return;
    }
    
    if (nickname && isConnected) {
        currentNickname = nickname;

        // 不再保存昵称到localStorage，每次刷新都需要重新输入

        hideNicknameModal();
        enableChatInput();

        // 发送加入消息
        sendWebSocketMessage({
            type: 'JOIN', senderNickname: nickname, content: '', timestamp: new Date().toISOString()
        });

        hasJoinedChat = true;

        // 确保sessionId可用
        window.sessionId = sessionId;
        window.hasJoinedChat = hasJoinedChat;
        
        // 保存会话状态到sessionStorage以便恢复
        sessionStorage.setItem('chatSessionId', sessionId);
        sessionStorage.setItem('chatNickname', currentNickname);
        sessionStorage.setItem('hasJoinedChat', 'true');
        sessionStorage.setItem('sessionTimestamp', Date.now().toString());
        
        // 触发管理员功能初始化
        if (typeof adminManager !== 'undefined') {
            setTimeout(() => {
                adminManager.checkAdminStatus();
            }, 1000);
        }

        showNotification('成功加入聊天室！', 'success');
    }
}

// 启用聊天输入
function enableChatInput() {
    messageInput.disabled = false;
    sendBtn.disabled = false;
    imageBtn.disabled = false;
    messageInput.focus();
}

// 禁用聊天输入
function disableChatInput() {
    messageInput.disabled = true;
    sendBtn.disabled = true;
    imageBtn.disabled = true;
}

// 连接WebSocket
function connectWebSocket() {
    // 首先尝试SockJS连接
    if (typeof SockJS !== 'undefined') {
        console.log('尝试使用SockJS连接...');
        tryConnectSockJS();
    } else {
        console.log('SockJS不可用，尝试原生WebSocket连接...');
        tryConnectNativeWebSocket();
    }
}

// 尝试SockJS连接
function tryConnectSockJS() {
    try {
        const sockjsUrl = '/websocket/chat';
        console.log(`尝试SockJS连接: ${sockjsUrl}`);

        websocket = new SockJS(sockjsUrl);
        setupWebSocketEvents();
    } catch (error) {
        console.error('SockJS连接失败:', error);
        tryConnectNativeWebSocket();
    }
}

// 尝试原生WebSocket连接
function tryConnectNativeWebSocket() {
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';

    // 尝试多个WebSocket端点
    const wsUrls = [`${protocol}//${window.location.host}/chat`  // 纯WebSocket
    ];

    tryConnectWebSocket(wsUrls, 0);
}

// 尝试连接WebSocket（支持多个端点）
function tryConnectWebSocket(urls, index) {
    if (index >= urls.length) {
        console.error('所有WebSocket端点连接失败');
        updateConnectionStatus(false);
        showNotification('连接失败，请检查服务器状态！', 'error');
        return;
    }

    const wsUrl = urls[index];
    console.log(`尝试连接WebSocket: ${wsUrl}`);

    try {
        websocket = new WebSocket(wsUrl);
        setupWebSocketEvents(urls, index);
    } catch (error) {
        console.error(`WebSocket连接失败: ${wsUrl}`, error);
        // 尝试下一个端点
        setTimeout(() => tryConnectWebSocket(urls, index + 1), 1000);
    }
}

// 设置WebSocket事件
function setupWebSocketEvents(urls, currentIndex) {
    websocket.onopen = function (event) {
        console.log('WebSocket连接已建立');
        isConnected = true;
        updateConnectionStatus(true);

        // 确保sessionId已设置
        if (!sessionId) {
            sessionId = getSessionId();
        }
        
        // 将sessionId设置为全局变量，供管理员功能使用
        window.sessionId = sessionId;
        window.hasJoinedChat = hasJoinedChat;

        // 如果已经有昵称，启用聊天输入并加入聊天
        if (currentNickname && !hasJoinedChat) {
            enableChatInput();

            // 自动加入聊天室
            setTimeout(() => {
                sendWebSocketMessage({
                    type: 'JOIN', senderNickname: currentNickname, content: '', timestamp: new Date().toISOString()
                });
                hasJoinedChat = true;
                window.hasJoinedChat = hasJoinedChat;
                // 更新sessionStorage
                sessionStorage.setItem('hasJoinedChat', 'true');
            }, 500);
        } else if (currentNickname && hasJoinedChat) {
            // 如果是重连，只启用输入框，不重复发送JOIN消息
            enableChatInput();
            console.log('WebSocket重连成功，恢复会话:', { sessionId, nickname: currentNickname });
            showNotification('重新连接成功！', 'success');
        }

        // 重置重连计数器
        reconnectAttempts = 0;

        // 隐藏重连按钮
        reconnectBtn.style.display = 'none';

        showNotification('连接成功！', 'success');
    };

    websocket.onmessage = function (event) {
        try {
            const message = JSON.parse(event.data);
            handleWebSocketMessage(message);
        } catch (error) {
            console.error('解析消息失败:', error);
        }
    };

    websocket.onclose = function (event) {
        console.log('WebSocket连接已关闭');
        isConnected = false;
        updateConnectionStatus(false);
        disableChatInput();

        // 尝试重连
        if (reconnectAttempts < maxReconnectAttempts) {
            reconnectAttempts++;
            const delay = Math.min(1000 * Math.pow(2, reconnectAttempts), 30000); // 指数退避，最大30秒

            setTimeout(() => {
                if (!isConnected) {
                    showNotification(`连接断开，正在重连... (${reconnectAttempts}/${maxReconnectAttempts})`, 'info');
                    connectWebSocket();
                }
            }, delay);
        } else {
            showNotification('连接失败次数过多，请点击重连按钮或刷新页面', 'error');
            reconnectBtn.style.display = 'inline-block';
        }
    };

    websocket.onerror = function (error) {
        console.error('WebSocket错误:', error);
        updateConnectionStatus(false);

        // 如果当前连接失败，尝试下一个端点
        if (urls && currentIndex !== undefined) {
            setTimeout(() => tryConnectWebSocket(urls, currentIndex + 1), 1000);
        } else {
            // 对于SockJS连接失败，尝试原生WebSocket
            setTimeout(() => {
                if (!isConnected) {
                    console.log('SockJS连接失败，尝试原生WebSocket...');
                    tryConnectNativeWebSocket();
                }
            }, 1000);
        }
    };
}

// 处理WebSocket消息
function handleWebSocketMessage(message) {
    console.log('收到消息:', message);

    // 如果消息包含sessionId，更新前端的sessionId（用于同步后端分配的真实sessionId）
    if (message.sessionId && message.type === 'SYSTEM' && message.content.includes('连接成功')) {
        const oldSessionId = sessionId;
        sessionId = message.sessionId;
        window.sessionId = sessionId;
        
        // 更新sessionStorage中的sessionId
        sessionStorage.setItem('chatSessionId', sessionId);
        console.log('同步后端sessionId:', oldSessionId, '->', sessionId);
    }

    // 更新在线人数
    if (message.onlineCount !== undefined) {
        updateOnlineCount(message.onlineCount);
    }

    // 处理在线人数更新消息（不显示在聊天区域）
    if (message.type === 'ONLINE_COUNT') {
        // 只更新在线人数，不显示消息
        return;
    }

    // 处理管理员相关消息
    if (message.type === 'ONLINE_USERS') {
        // 处理在线用户列表响应
        if (adminManager) {
            adminManager.handleOnlineUsersResponse(message.onlineUsers);
            // 检查当前用户是否为管理员
            const currentUser = message.onlineUsers.find(user => user.sessionId === sessionId);
            if (currentUser && currentUser.userType === 'ADMIN') {
                adminManager.showAdminButton();
            } else {
                adminManager.hideAdminButton();
            }
        }
        return;
    }

    // 处理系统消息，特别是昵称重复错误
    if (message.type === 'SYSTEM' && message.content.includes('加入失败')) {
        // 显示错误消息并重新显示昵称设置模态框
        showNotification(message.content, 'error');
        showNicknameModal();
        return;
    }

    if (message.type === 'ADMIN_OPERATION_RESULT') {
        // 处理管理员操作结果
        if (adminManager) {
            adminManager.handleAdminOperationResult(message);
        }
        return;
    }

    if (message.type === 'ADMIN_KICK_USER') {
        // 处理被踢出消息
        if (adminManager) {
            adminManager.handleKickMessage();
        }
        return;
    }

    if (message.type === 'RATE_LIMIT_WARNING') {
        // 处理频率限制警告
        showNotification(message.content, 'warning');
        return;
    }

    // 显示消息
    displayMessage(message);
    
    // 如果是用户加入消息，刷新在线用户列表
    if (message.type === 'JOIN' && adminManager) {
        setTimeout(() => {
            adminManager.requestOnlineUsers();
        }, 1000);
    }
}

// 发送WebSocket消息
function sendWebSocketMessage(message) {
    if (websocket && websocket.readyState === WebSocket.OPEN) {
        websocket.send(JSON.stringify(message));
    } else {
        showNotification('连接已断开，无法发送消息！', 'error');
    }
}

// 发送聊天消息
function sendMessage() {
    const content = messageInput.value.trim();
    if (!content || !isConnected || !currentNickname) {
        return;
    }

    const message = {
        type: 'TEXT', senderNickname: currentNickname, content: content, timestamp: new Date().toISOString()
    };

    sendWebSocketMessage(message);
    messageInput.value = '';
    charCountElement.textContent = '0';
    charCountElement.style.color = '#999';
}

// 处理图片选择
function handleImageSelect(event) {
    const file = event.target.files[0];
    if (!file) return;

    // 验证文件类型
    if (!file.type.startsWith('image/')) {
        showNotification('只能上传图片文件！', 'error');
        return;
    }

    // 验证文件大小 (5MB)
    if (file.size > 5 * 1024 * 1024) {
        showNotification('图片大小不能超过5MB！', 'error');
        return;
    }

    // 上传图片
    uploadImage(file);

    // 清空input
    event.target.value = '';
}

// 上传图片到服务器
function uploadImage(file) {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('sessionId', getSessionId());

    // 显示上传进度
    showNotification('正在上传图片...', 'info');

    fetch('/api/upload/image', {
        method: 'POST', body: formData
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 发送图片消息
                sendImageMessage(data.imageUrl);
            } else {
                showNotification('上传失败: ' + data.message, 'error');
            }
        })
        .catch(error => {
            console.error('图片上传失败:', error);
            showNotification('图片上传失败，请重试！', 'error');
        });
}

// 发送图片消息
function sendImageMessage(imageUrl) {
    if (!isConnected || !currentNickname) {
        return;
    }

    const message = {
        type: 'IMAGE',
        senderNickname: currentNickname,
        content: '[图片]',
        imageUrl: imageUrl,
        timestamp: new Date().toISOString()
    };

    sendWebSocketMessage(message);
}

// 获取会话ID
function getSessionId() {
    if (!sessionId) {
        // 首先尝试从sessionStorage恢复
        const savedSessionId = sessionStorage.getItem('chatSessionId');
        if (savedSessionId) {
            sessionId = savedSessionId;
            console.log('恢复保存的sessionId:', sessionId);
        } else {
            sessionId = generateSessionId();
            // 保存到sessionStorage
            sessionStorage.setItem('chatSessionId', sessionId);
            console.log('生成新的sessionId:', sessionId);
        }
    }
    return sessionId;
}

// 生成会话ID
function generateSessionId() {
    return 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
}

// 处理@建议功能
function handleAtSuggestion(inputValue) {
    const cursorPosition = messageInput.selectionStart;
    const beforeCursor = inputValue.substring(0, cursorPosition);

    // 检查是否在输入@
    if (beforeCursor.endsWith('@')) {
        showAtSuggestion();
    } else {
        hideAtSuggestion();
    }
}

// 显示@建议
function showAtSuggestion() {
    if (showingAtSuggestion) return;

    showingAtSuggestion = true;

    // 创建建议框
    const suggestionBox = document.createElement('div');
    suggestionBox.id = 'atSuggestionBox';
    suggestionBox.className = 'at-suggestion-box';
    suggestionBox.innerHTML = `
        <div class="at-suggestion-item active" onclick="selectAtSuggestion()">
            <i class="fas fa-robot"></i>
            <span>zut机器人</span>
            <small>AI助手</small>
        </div>
    `;

    // 插入到输入容器中
    const inputContainer = document.querySelector('.input-container');
    inputContainer.appendChild(suggestionBox);

    // 显示提示
    showNotification('按Tab键或点击选择zut机器人', 'info');
}

// 隐藏@建议
function hideAtSuggestion() {
    if (!showingAtSuggestion) return;

    showingAtSuggestion = false;
    const suggestionBox = document.getElementById('atSuggestionBox');
    if (suggestionBox) {
        suggestionBox.remove();
    }
}

// 选择@建议
function selectAtSuggestion() {
    const inputValue = messageInput.value;
    const cursorPosition = messageInput.selectionStart;

    // 找到最后一个@的位置
    const beforeCursor = inputValue.substring(0, cursorPosition);
    const lastAtIndex = beforeCursor.lastIndexOf('@');

    if (lastAtIndex !== -1) {
        // 替换@为@zut机器人
        const newValue = inputValue.substring(0, lastAtIndex) + '@zut机器人 ' + inputValue.substring(cursorPosition);
        messageInput.value = newValue;

        // 设置光标位置
        const newCursorPosition = lastAtIndex + '@zut机器人 '.length;
        messageInput.setSelectionRange(newCursorPosition, newCursorPosition);
        messageInput.focus();
    }

    hideAtSuggestion();
}

// 显示图片预览模态框
function showImageModal(imageUrl) {
    modalImage.src = imageUrl;
    imageModal.classList.add('show');
}

// 隐藏图片预览模态框
function hideImageModal() {
    imageModal.classList.remove('show');
    modalImage.src = '';
}

// 显示消息
function displayMessage(message) {
    const messageElement = document.createElement('div');
    messageElement.className = 'message';

    // 确定消息类型和样式
    if (message.type === 'SYSTEM' || message.type === 'JOIN' || message.type === 'LEAVE') {
        messageElement.classList.add('system');
        messageElement.innerHTML = `
            <div class="message-content">${processLinks(message.content)}</div>
        `;
    } else if (message.type === 'IMAGE') {
        // 图片消息
        const isOwnMessage = message.senderNickname === currentNickname;
        messageElement.classList.add(isOwnMessage ? 'own' : 'other');

        const timeStr = formatTime(message.timestamp);
        messageElement.innerHTML = `
            <div class="message-header">
                <span class="sender-name">${escapeHtml(message.senderNickname)}</span>
                <span class="message-time">${timeStr}</span>
            </div>
            <div class="message-content">
                <img class="message-image" src="${escapeHtml(message.imageUrl)}" 
                     alt="图片消息" onclick="showImageModal('${escapeHtml(message.imageUrl)}')"
                     onerror="this.style.display='none'; this.parentNode.innerHTML='<span style=\\'color: #999;\\'>图片加载失败</span>'">
            </div>
        `;
    } else if (message.type === 'GIFT') {
        // 礼物消息
        messageElement.classList.add('gift');

        const timeStr = formatTime(message.timestamp);
        messageElement.innerHTML = `
            <div class="message-header">
                <span class="sender-name">
                    <i class="fas fa-gift"></i>
                    ${escapeHtml(message.senderNickname)}
                </span>
                <span class="message-time">${timeStr}</span>
            </div>
            <div class="message-content">
                <img src="${escapeHtml(message.giftIcon)}" alt="${escapeHtml(message.giftName)}" 
                     style="width: 24px; height: 24px; margin-right: 8px; vertical-align: middle;">
                ${escapeHtml(message.content)}
                <span style="color: #ff6b6b; font-weight: bold; margin-left: 8px;">${message.giftValue}金币</span>
            </div>
        `;

        // 如果不是自己发送的礼物，播放动画
        if (message.senderNickname !== currentNickname) {
            setTimeout(() => {
                playGiftAnimation({
                    name: message.giftName,
                    icon: message.giftIcon,
                    animation: message.giftAnimation,
                    value: message.giftValue
                });
            }, 100);
        }
    } else if (message.type === 'VIDEO') {
        // 视频消息
        const isOwnMessage = message.senderNickname === currentNickname;
        messageElement.classList.add(isOwnMessage ? 'own' : 'other', 'video-message');

        const timeStr = formatTime(message.timestamp);
        const videoTitle = message.videoTitle || '视频';
        messageElement.innerHTML = `
            <div class="message-header">
                <span class="sender-name">
                    <i class="fas fa-video"></i>
                    ${escapeHtml(message.senderNickname)}
                </span>
                <span class="message-time">${timeStr}</span>
            </div>
            <div class="message-content">
                <div class="video-message-content">
                    <p class="video-description">${processLinks(message.content)}</p>
                    <div class="video-container">
                        <video class="message-video" controls preload="metadata" 
                               onerror="this.style.display='none'; this.parentNode.innerHTML='<div class=\\'video-loading\\'>视频加载失败</div>'">
                            <source src="${escapeHtml(message.videoUrl)}" type="video/mp4">
                            您的浏览器不支持视频播放
                        </video>
                        <div class="video-info">
                            <span class="video-title">小视频</span>
                        </div>
                    </div>
                </div>
            </div>
        `;
    } else if (message.type === 'AI_ROBOT') {
        // AI机器人消息
        messageElement.classList.add('ai-robot');

        const timeStr = formatTime(message.timestamp);
        messageElement.innerHTML = `
            <div class="message-header">
                <span class="sender-name">
                    <i class="fas fa-robot"></i>
                    ${escapeHtml(message.senderNickname)}
                </span>
                <span class="message-time">${timeStr}</span>
            </div>
            <div class="message-content">${processLinks(message.content)}</div>
        `;
    } else {
        // 文本消息
        const isOwnMessage = message.senderNickname === currentNickname;
        messageElement.classList.add(isOwnMessage ? 'own' : 'other');

        const timeStr = formatTime(message.timestamp);
        messageElement.innerHTML = `
            <div class="message-header">
                <span class="sender-name">${escapeHtml(message.senderNickname)}</span>
                <span class="message-time">${timeStr}</span>
            </div>
            <div class="message-content">${processLinks(message.content)}</div>
        `;
    }

    messagesList.appendChild(messageElement);
    scrollToBottom();
}

// 更新在线人数
function updateOnlineCount(count) {
    onlineCountElement.textContent = count;
    // 为移动端添加title属性
    const onlineCountContainer = document.querySelector('.online-count');
    if (onlineCountContainer) {
        onlineCountContainer.setAttribute('title', `${count}人在线`);
    }
}

// 更新连接状态
function updateConnectionStatus(connected) {
    if (connected) {
        connectionStatusElement.innerHTML = '<i class="fas fa-circle"></i> 已连接';
        connectionStatusElement.className = 'connection-status connected';
    } else {
        connectionStatusElement.innerHTML = '<i class="fas fa-circle"></i> 未连接';
        connectionStatusElement.className = 'connection-status disconnected';
    }
}

// 滚动到底部
function scrollToBottom() {
    const container = document.getElementById('messagesContainer');
    container.scrollTop = container.scrollHeight;
}

// 格式化时间
function formatTime(timestamp) {
    const date = new Date(timestamp);
    const now = new Date();
    const diffMs = now - date;
    const diffMins = Math.floor(diffMs / 60000);

    if (diffMins < 1) {
        return '刚刚';
    } else if (diffMins < 60) {
        return `${diffMins}分钟前`;
    } else if (date.toDateString() === now.toDateString()) {
        return date.toLocaleTimeString('zh-CN', {hour: '2-digit', minute: '2-digit'});
    } else {
        return date.toLocaleString('zh-CN', {
            month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit'
        });
    }
}

// HTML转义
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// 处理文本中的链接，将http/https链接转换为可点击的链接
function processLinks(text) {
    // 首先转义HTML
    let processedText = escapeHtml(text);
    
    // 1. 匹配完整的http和https链接
    const fullUrlRegex = /(https?:\/\/[^\s<>"']+)/gi;
    processedText = processedText.replace(fullUrlRegex, function(url) {
        return createClickableLink(url, url);
    });
    
    // 2. 匹配www开头的链接（添加https前缀）
    const wwwRegex = /(?<!https?:\/\/)(www\.[^\s<>"']+)/gi;
    processedText = processedText.replace(wwwRegex, function(url) {
        const fullUrl = 'https://' + url;
        return createClickableLink(fullUrl, url);
    });
    
    return processedText;
}

// 创建可点击的链接
function createClickableLink(fullUrl, displayText) {
    // 移除末尾可能的标点符号
    let cleanUrl = fullUrl;
    let cleanDisplayText = displayText;
    let suffix = '';
    
    // 检查末尾是否有标点符号
    const punctuation = /[.,;:!?)]$/;
    if (punctuation.test(fullUrl)) {
        cleanUrl = fullUrl.slice(0, -1);
        cleanDisplayText = displayText.slice(0, -1);
        suffix = fullUrl.slice(-1);
    }
    
    // 限制显示的URL长度
    let shortDisplayText = cleanDisplayText;
    if (cleanDisplayText.length > 45) {
        shortDisplayText = cleanDisplayText.substring(0, 42) + '...';
    }
    
    // 返回可点击的链接HTML，添加安全确认和图标
    return `<a href="${cleanUrl}" target="_blank" rel="noopener noreferrer" class="message-link" title="${cleanUrl}" onclick="return confirmExternalLink('${cleanUrl.replace(/'/g, '\\\'')}')">${shortDisplayText} <i class="fas fa-external-link-alt"></i></a>${suffix}`;
}

// 确认外部链接跳转
function confirmExternalLink(url) {
    const domain = url.replace(/^https?:\/\//, '').split('/')[0];
    return confirm(`即将跳转到外部网站：\n${domain}\n\n确定要继续吗？`);
}

// 显示通知
function showNotification(message, type = 'info') {
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.textContent = message;

    const container = document.getElementById('notifications');
    container.appendChild(notification);

    // 3秒后自动移除
    setTimeout(() => {
        if (notification.parentNode) {
            notification.parentNode.removeChild(notification);
        }
    }, 3000);
}

// 切换emoji面板
function toggleEmojiPanel() {
    emojiPanel.classList.toggle('show');
}

// 隐藏emoji面板
function hideEmojiPanel() {
    emojiPanel.classList.remove('show');
}

// 切换表情包面板
function toggleStickerPanel() {
    console.log('切换表情包面板');
    if (stickerPanel.classList.contains('show')) {
        hideStickerPanel();
    } else {
        showStickerPanel();
    }
}

// 显示表情包面板
function showStickerPanel() {
    hideEmojiPanel(); // 关闭emoji面板
    stickerPanel.classList.add('show');

    // 如果还没有加载过表情包，则加载第一页
    if (stickerGrid.children.length === 0) {
        console.log('开始加载表情包...');
        // 直接调用API加载表情包
        loadStickers(1);
    }
}

// 隐藏表情包面板
function hideStickerPanel() {
    stickerPanel.classList.remove('show');
}

// 加载表情包
function loadStickers(page = 1) {
    if (isLoadingStickers) return;

    isLoadingStickers = true;
    stickerLoading.style.display = 'flex';

    // 使用后端代理API避免跨域问题
    const apiUrl = `/api/sticker/list?page=${page}&perPage=16&keyword=changyong&appId=wx2f23b155ee1d2ae1`;
    console.log('正在请求代理API:', apiUrl);

    fetch(apiUrl, {
        method: 'GET', headers: {
            'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/json'
        }
    })
        .then(response => response.json())
        .then(data => {
            console.log('API响应数据:', data);

            // 根据新API的响应格式处理
            let stickerList = [];
            let totalCount = 0;

            if (data && data.code === 0 && data.data) {
                // 新API格式: {code: 1, msg: "请求成功", data: {count: x, rows: [...]}}
                if (data.data.data && Array.isArray(data.data.data)) {
                    stickerList = data.data.data;
                    totalCount = Math.ceil((data.data.total || data.data.total.length) / 16) || 1;
                }
            } else if (data && data.code === 200 && data.data) {
                // 备用格式1: {code: 200, data: {list: [...], totalPage: x}}
                if (data.data.list) {
                    stickerList = data.data.list;
                    totalCount = data.data.totalPage || 1;
                } else if (data.data.rows) {
                    stickerList = data.data.rows;
                    totalCount = Math.ceil(data.data.count / 16) || 1;
                } else if (Array.isArray(data.data)) {
                    stickerList = data.data;
                    totalCount = 1;
                }
            } else if (data && Array.isArray(data)) {
                // 格式3: 直接返回数组
                stickerList = data;
                totalCount = 1;
            }

            if (stickerList.length > 0) {
                displayStickers(stickerList, page === 1);
                currentPage = page;
                totalPages = totalCount;
                updatePagination();
            } else {
                console.error('API返回格式错误或无数据:', data);
                showNotification('表情包数据格式错误', 'error');

                // 显示无数据状态
                stickerGrid.innerHTML = `
                    <div class="sticker-empty">
                        <i class="fas fa-inbox"></i>
                        <h5>暂无表情包</h5>
                        <p>API返回数据格式不正确</p>
                    </div>
                `;
            }
        })
        .catch(error => {
            console.error('加载表情包失败:', error);
            showNotification('网络错误，无法加载表情包', 'error');

            // 显示错误状态
            stickerGrid.innerHTML = `
                <div class="sticker-empty">
                    <i class="fas fa-exclamation-triangle"></i>
                    <h5>加载失败</h5>
                    <p>网络连接错误，请稍后重试</p>
                </div>
            `;
        })
        .finally(() => {
            isLoadingStickers = false;
            stickerLoading.style.display = 'none';
        });
}

// 显示表情包
function displayStickers(stickers, clearGrid = true) {
    if (clearGrid) {
        stickerGrid.innerHTML = '';
    }

    stickers.forEach((sticker, index) => {
        const stickerItem = document.createElement('div');
        stickerItem.className = 'sticker-item';

        // 获取图片URL，支持多种数据格式
        let originalUrl = sticker.imgurl || sticker.path || sticker.url || sticker.src || '';
        let stickerName = sticker.name || sticker.imgName || sticker.imgDescribe || sticker.title || '表情包';

        console.log(`表情包${index}:`, {
            originalUrl, stickerName, stickerData: sticker
        });

        // 如果没有图片URL，跳过这个表情包
        if (!originalUrl) {
            console.warn('表情包没有图片URL:', sticker);
            return;
        }

        // 创建图片元素
        const img = document.createElement('img');
        img.src = originalUrl;
        img.alt = stickerName;
        img.style.width = '100%';
        img.style.height = '100%';
        img.style.objectFit = 'cover';
        img.style.display = 'block';

        // 图片加载成功处理
        img.onload = function () {
            // 图片加载成功
        };

        // 图片加载失败处理
        img.onerror = function () {
            // 显示一个占位符
            this.src = '';
            this.alt = '加载失败';
        };

        // 设置点击事件
        stickerItem.onclick = () => sendStickerMessage(originalUrl, stickerName);

        stickerItem.appendChild(img);
        stickerGrid.appendChild(stickerItem);
    });
}

// 发送表情包消息
function sendStickerMessage(imageUrl, altText) {
    if (!isConnected || !currentNickname) {
        showNotification('请先连接聊天室', 'error');
        return;
    }

    const message = {
        type: 'IMAGE',
        senderNickname: currentNickname,
        content: `[表情包: ${altText}]`,
        imageUrl: imageUrl,
        timestamp: new Date().toISOString()
    };

    sendWebSocketMessage(message);
    hideStickerPanel();
}

// 更新分页按钮状态
function updatePagination() {
    prevPageBtn.disabled = currentPage <= 1;
    nextPageBtn.disabled = currentPage >= totalPages;
    pageInfo.textContent = `第${currentPage}页 / 共${totalPages}页`;
}

// 加载上一页
function loadPreviousPage() {
    if (currentPage > 1) {
        loadStickers(currentPage - 1);
    }
}

// 加载下一页
function loadNextPage() {
    if (currentPage < totalPages) {
        loadStickers(currentPage + 1);
    }
}

// 加载本地表情包（备用方案）


// 插入emoji
function insertEmoji(emoji) {
    const input = messageInput;
    const startPos = input.selectionStart;
    const endPos = input.selectionEnd;
    const textBefore = input.value.substring(0, startPos);
    const textAfter = input.value.substring(endPos);

    input.value = textBefore + emoji + textAfter;
    input.selectionStart = input.selectionEnd = startPos + emoji.length;
    input.focus();

    // 更新字符计数
    const event = new Event('input');
    input.dispatchEvent(event);

    hideEmojiPanel();
}

// 页面卸载时断开连接
window.addEventListener('beforeunload', function () {
    if (websocket && currentNickname) {
        sendWebSocketMessage({
            type: 'LEAVE', senderNickname: currentNickname, content: '', timestamp: new Date().toISOString()
        });
    }
});

// 页面可见性变化时的处理
document.addEventListener('visibilitychange', function () {
    if (document.hidden) {
        // 页面隐藏时暂停某些操作
    } else {
        // 页面重新可见时恢复操作
        if (!isConnected) {
            connectWebSocket();
        }
    }
});

// 全屏功能
function toggleFullscreen() {
    if (!document.fullscreenElement && !document.webkitFullscreenElement && !document.mozFullScreenElement && !document.msFullscreenElement) {
        // 进入全屏
        const element = document.documentElement;
        if (element.requestFullscreen) {
            element.requestFullscreen();
        } else if (element.webkitRequestFullscreen) {
            element.webkitRequestFullscreen();
        } else if (element.mozRequestFullScreen) {
            element.mozRequestFullScreen();
        } else if (element.msRequestFullscreen) {
            element.msRequestFullscreen();
        }
    } else {
        // 退出全屏
        if (document.exitFullscreen) {
            document.exitFullscreen();
        } else if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen();
        } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else if (document.msExitFullscreen) {
            document.msExitFullscreen();
        }
    }
}

// 更新全屏按钮图标
function updateFullscreenButton() {
    const isFullscreen = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;

    const icon = fullscreenBtn.querySelector('i');
    if (isFullscreen) {
        icon.className = 'fas fa-compress';
        fullscreenBtn.title = '退出全屏';
    } else {
        icon.className = 'fas fa-expand';
        fullscreenBtn.title = '全屏';
    }
}

// 退出聊天功能
function exitChat() {
    if (confirm('确定要退出聊天室吗？')) {
        isLeavingChat = true;

        // 发送离开消息
        if (websocket && currentNickname && isConnected) {
            const leaveMessage = {
                type: 'LEAVE',
                senderNickname: currentNickname,
                content: currentNickname + ' 离开了聊天室',
                timestamp: new Date().toISOString()
            };

            try {
                sendWebSocketMessage(leaveMessage);
                // 等待一小段时间确保消息发送完成
                setTimeout(() => {
                    if (websocket) {
                        websocket.close();
                    }
                }, 100);
            } catch (error) {
                console.error('发送离开消息失败:', error);
                if (websocket) {
                    websocket.close();
                }
            }
        }

        // 延迟重置状态，确保离开消息发送完成
        setTimeout(() => {
            // 重置状态
            currentNickname = '';
            isConnected = false;
            hasJoinedChat = false;
            isLeavingChat = false;

            // 清除保存的昵称和会话状态（用户主动退出）
            localStorage.removeItem('chatNickname');
            sessionStorage.clear();
            console.log('用户主动退出，清除会话状态');

            // 清空消息列表
            messagesList.innerHTML = '';

            // 显示昵称模态框
            showNicknameModal();

            // 重置输入框
            messageInput.value = '';
            nicknameInput.value = '';
            charCountElement.textContent = '0';
            disableChatInput();

            // 更新连接状态
            updateConnectionStatus(false);
            updateOnlineCount(0);

            showNotification('已退出聊天室', 'info');
        }, 200);
    }
}

// 确认退出页面时的处理
window.addEventListener('beforeunload', function (e) {
    if (isConnected && currentNickname && !isLeavingChat) {
        isLeavingChat = true;

        console.log('页面刷新/关闭，发送离开消息');

        // 发送离开消息
        sendWebSocketMessage({
            type: 'LEAVE', senderNickname: currentNickname, content: '', timestamp: new Date().toISOString()
        });
    }
});

// 手动重连函数
function manualReconnect() {
    reconnectAttempts = 0; // 重置重连计数器
    reconnectBtn.style.display = 'none'; // 隐藏重连按钮

    // 关闭现有连接
    if (websocket) {
        websocket.close();
    }

    showNotification('正在重新连接...', 'info');

    // 延迟一下再重连
    setTimeout(() => {
        connectWebSocket();
    }, 1000);
}

// ==================== 礼物功能 ====================

// 礼物相关变量
let gifts = [];
let isLoadingGifts = false;

// 切换礼物面板
function toggleGiftPanel() {
    if (giftPanel.classList.contains('show')) {
        hideGiftPanel();
    } else {
        showGiftPanel();
    }
}

// 显示礼物面板
function showGiftPanel() {
    giftPanel.classList.add('show');

    // 如果还没有加载礼物，则加载
    if (gifts.length === 0 && !isLoadingGifts) {
        loadGifts();
    }
}

// 隐藏礼物面板
function hideGiftPanel() {
    giftPanel.classList.remove('show');
}

// 加载礼物列表
function loadGifts() {
    if (isLoadingGifts) return;

    isLoadingGifts = true;
    showGiftLoading();

    fetch('/api/gifts/list')
        .then(response => response.json())
        .then(result => {
            if (result.success) {
                gifts = result.data;
                displayGifts(gifts);
                console.log('礼物列表加载成功，共', gifts.length, '个礼物');
            } else {
                console.error('加载礼物列表失败:', result.message);
                showNotification('加载礼物列表失败：' + result.message, 'error');
            }
        })
        .catch(error => {
            console.error('加载礼物列表出错:', error);
            showNotification('加载礼物列表失败，请重试！', 'error');
        })
        .finally(() => {
            isLoadingGifts = false;
            hideGiftLoading();
        });
}

// 显示礼物加载状态
function showGiftLoading() {
    giftLoading.style.display = 'flex';
    giftGrid.innerHTML = '';
}

// 隐藏礼物加载状态
function hideGiftLoading() {
    giftLoading.style.display = 'none';
}

// 显示礼物列表
function displayGifts(giftList) {
    giftGrid.innerHTML = '';

    giftList.forEach((gift, index) => {
        const giftItem = document.createElement('div');
        giftItem.className = 'gift-item';
        giftItem.style.animationDelay = `${index * 0.05}s`;

        giftItem.innerHTML = `
            <img class="gift-icon" src="${gift.icon}" alt="${gift.name}" onerror="this.src='/image/窝草.png'">
            <div class="gift-name">${gift.name}</div>
            <div class="gift-value">${gift.value}金币</div>
        `;

        giftItem.addEventListener('click', () => {
            sendGiftMessage(gift);
        });

        giftGrid.appendChild(giftItem);
    });
}

// 发送礼物消息
function sendGiftMessage(gift) {
    if (!isConnected || !currentNickname) {
        showNotification('请先连接聊天室', 'error');
        return;
    }

    const message = {
        type: 'GIFT',
        senderNickname: currentNickname,
        content: `送出了 ${gift.name}`,
        giftName: gift.name,
        giftIcon: gift.icon,
        giftAnimation: gift.animation,
        giftValue: gift.value,
        timestamp: new Date().toISOString()
    };

    sendWebSocketMessage(message);
    hideGiftPanel();

    // 播放礼物动画
    playGiftAnimation(gift);

    showNotification(`成功送出 ${gift.name}！`, 'success');
}

// 测试礼物特效函数（调试用）
function testGiftEffect() {
    const testGift = {
        name: '爱心直升机', icon: '/image/爱心直升机.png', animation: '/image/爱心直升机.svga', value: 888
    };
    playGiftAnimation(testGift);
}

// 在控制台暴露测试函数
window.testGiftEffect = testGiftEffect;

// 播放礼物动画
function playGiftAnimation(gift) {
    console.log('播放礼物动画:', gift);

    // 创建全屏动画容器
    const animationContainer = document.createElement('div');
    animationContainer.className = 'gift-animation-container';
    animationContainer.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100vw;
        height: 100vh;
        pointer-events: none;
        z-index: 9999;
        display: flex;
        align-items: center;
        justify-content: center;
    `;
    document.body.appendChild(animationContainer);

    // 创建动画元素
    const animationDiv = document.createElement('div');
    animationDiv.className = 'gift-animation';
    animationDiv.style.cssText = `
        width: 80vmin;
        height: 80vmin;
        max-width: 600px;
        max-height: 600px;
        position: relative;
    `;
    animationContainer.appendChild(animationDiv);

    // 尝试使用SVGA播放器播放动画
    if (typeof SVGA !== 'undefined') {
        try {
            const player = new SVGA.Player(animationDiv);
            const parser = new SVGA.Parser();

            console.log('尝试加载SVGA动画:', gift.animation);

            parser.load(gift.animation, (videoItem) => {
                console.log('SVGA动画加载成功');
                player.setVideoItem(videoItem);
                player.startAnimation();

                // 动画播放完成后清理
                setTimeout(() => {
                    if (animationContainer.parentNode) {
                        animationContainer.parentNode.removeChild(animationContainer);
                    }
                }, 4000);
            }, (error) => {
                console.warn('SVGA动画加载失败:', error);
                // 如果SVGA加载失败，显示增强的特效
                showEnhancedGiftEffect(gift, animationContainer);
            });
        } catch (error) {
            console.warn('SVGA播放器创建失败:', error);
            showEnhancedGiftEffect(gift, animationContainer);
        }
    } else {
        console.warn('SVGA库未加载，显示增强特效');
        showEnhancedGiftEffect(gift, animationContainer);
    }
}

// 显示增强的礼物特效（备用方案）
function showEnhancedGiftEffect(gift, container) {
    console.log('显示增强礼物特效:', gift);

    // 清空容器
    container.innerHTML = '';

    // 创建特效内容
    const effectContent = document.createElement('div');
    effectContent.style.cssText = `
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
        animation: giftEnhancedShow 3s ease-out forwards;
    `;

    // 创建背景光效
    const bgEffect = document.createElement('div');
    bgEffect.style.cssText = `
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: radial-gradient(circle, rgba(255,107,107,0.3) 0%, rgba(255,107,107,0.1) 50%, transparent 100%);
        animation: giftBgPulse 2s ease-in-out infinite;
    `;
    effectContent.appendChild(bgEffect);

    // 创建礼物图标容器
    const giftContainer = document.createElement('div');
    giftContainer.style.cssText = `
        position: relative;
        z-index: 2;
        display: flex;
        flex-direction: column;
        align-items: center;
        animation: giftBounce 1.5s ease-out;
    `;

    // 礼物图标
    const giftIcon = document.createElement('img');
    giftIcon.src = gift.icon;
    giftIcon.alt = gift.name;
    giftIcon.style.cssText = `
        width: 200px;
        height: 200px;
        object-fit: contain;
        margin-bottom: 20px;
        filter: drop-shadow(0 0 20px rgba(255,107,107,0.6));
        animation: giftIconScale 2s ease-in-out;
    `;

    // 如果图标加载失败，显示默认图标
    giftIcon.onerror = function () {
        const defaultIcon = document.createElement('div');
        defaultIcon.style.cssText = `
            font-size: 200px;
            width: 200px;
            height: 200px;
            display: flex;
            align-items: center;
            justify-content: center;
            text-shadow: 0 0 20px rgba(255,107,107,0.8);
            filter: drop-shadow(0 0 20px rgba(255,107,107,0.6));
            animation: giftIconScale 2s ease-in-out;
        `;
        defaultIcon.textContent = '🎁';
        this.parentNode.replaceChild(defaultIcon, this);
    };

    giftContainer.appendChild(giftIcon);

    // 礼物名称
    const giftName = document.createElement('div');
    giftName.textContent = gift.name;
    giftName.style.cssText = `
        font-size: 32px;
        font-weight: bold;
        color: #ff6b6b;
        margin-bottom: 10px;
        text-shadow: 0 2px 10px rgba(0,0,0,0.3);
        animation: giftTextGlow 1s ease-in-out infinite alternate;
    `;
    giftContainer.appendChild(giftName);

    // 礼物价值
    // const giftValue = document.createElement('div');
    // // giftValue.textContent = `${gift.value}金币`;
    // giftValue.style.cssText = `
    //     font-size: 24px;
    //     font-weight: 600;
    //     color: #ffd700;
    //     background: linear-gradient(45deg, #ff6b6b, #ee5a24);
    //     padding: 8px 20px;
    //     border-radius: 25px;
    //     box-shadow: 0 4px 15px rgba(255,107,107,0.4);
    //     text-shadow: 0 1px 3px rgba(0,0,0,0.3);
    // `;
    // giftContainer.appendChild(giftValue);

    effectContent.appendChild(giftContainer);

    // 添加粒子效果
    for (let i = 0; i < 20; i++) {
        const particle = document.createElement('div');
        particle.style.cssText = `
            position: absolute;
            width: 6px;
            height: 6px;
            background: #ff6b6b;
            border-radius: 50%;
            animation: giftParticle 3s ease-out infinite;
            animation-delay: ${i * 0.1}s;
            left: ${Math.random() * 100}%;
            top: ${Math.random() * 100}%;
        `;
        effectContent.appendChild(particle);
    }

    container.appendChild(effectContent);

    // 3秒后移除特效
    setTimeout(() => {
        if (container.parentNode) {
            container.parentNode.removeChild(container);
        }
    }, 3000);
}

// 显示简单礼物特效（最简备用方案）
function showSimpleGiftEffect(gift) {
    const effect = document.createElement('div');
    effect.style.cssText = `
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: white;
        border: 3px solid #ff6b6b;
        border-radius: 20px;
        padding: 30px;
        text-align: center;
        z-index: 2000;
        box-shadow: 0 20px 60px rgba(0,0,0,0.3);
        animation: giftSimpleShow 2s ease-out forwards;
    `;

    effect.innerHTML = `
        <div style="font-size: 48px; margin-bottom: 10px;">🎁</div>
        <div style="font-size: 18px; font-weight: bold; color: #ff6b6b; margin-bottom: 5px;">${gift.name}</div>
        <div style="font-size: 14px; color: #666;">${gift.value}金币</div>
    `;

    document.body.appendChild(effect);

    setTimeout(() => {
        if (effect.parentNode) {
            effect.parentNode.removeChild(effect);
        }
    }, 2000);
}


